#include							"UdpSocket.h"

UdpSocket::UdpSocket(boost::asio::io_service & service) : _socket(service, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 4244)), ASocket(0)
{
	_type = ASocket::UDP;
}

UdpSocket::~UdpSocket()
{

}

void								UdpSocket::_receive(const boost::system::error_code & error, size_t size)
{
  if (!error)
    {
      if (size > 0)
	{
	  _current_msg = size;
	  _handler->harvest(this);
	}
      else
	std::cout << size << std::endl;
      _startRead();
    }
  else
    {
      std::cout << "UDP error :" << error.message() << std::endl;
      close();
    }
}

void								UdpSocket::start()
{
	std::cout << "[INFO] Started UDP server on port " << _socket.local_endpoint().port() << std::endl;
	_startRead();
}

void								UdpSocket::close()
{
  	_socket.close();
}

boost::asio::ip::udp::socket		&UdpSocket::getSocket()
{
	return _socket;
}

void								UdpSocket::_startRead()
{
  if (_socket.is_open())
    _socket.async_receive_from(boost::asio::buffer(_buffer, 4096), _sender, boost::bind(&UdpSocket::_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
  else
    std::cout << "disconnected" << std::endl;

}

std::string							UdpSocket::getIp() const
{
	return _sender.address().to_string();
}
